<template>
  <!-- 转派弹框 -->
  <div class="transfer-dialog">
    <el-dialog
      :title="dialogTitle"
      :center="true"
      :visible.sync="dialogOpen"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="dialogClose"
      :before-close="dialogCancel"
      append-to-body
    >
      <el-form
        v-show="transferDialog"
        :rules="rules"
        ref="ruleForm"
        :model="listQuery"
        label-width="160px"
      >
        <el-row class="transfer-dialog-title"
          >当前已选择{{ allMsg.totalAcount }}个案件，共{{
            allMsg.totalEntity
          }}个实体，案件总金额{{ allMsg.totalCaseMoney }}元。</el-row
        >
        <el-row>
          <el-form-item label="分配模式" prop="distributionMode">
            <el-radio-group
              v-model="listQuery.distributionMode"
              @change="distributionModeChange"
            >
              <el-radio
                :label="item.code"
                v-for="item in $dict.getDictData('DistributionMode')"
                :key="item.code"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="配平方式" prop="balanceWay">
            <el-radio-group v-model="listQuery.balanceWay">
              <el-radio
                :label="item.code"
                v-for="item in $dict.getDictData('BalanceWay')"
                :key="item.code"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="配平维度" prop="balanceDimension">
            <el-radio-group v-model="listQuery.balanceDimension">
              <el-radio
                :label="item.code"
                v-for="item in $dict.getDictData('BalanceDimension')"
                :key="item.code"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="非延滞账户参与配平" prop="state">
            <el-radio-group v-model="listQuery.state">
              <el-radio
                :label="item.code"
                v-for="item in $dict.getDictData('State')"
                :key="item.code"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="转手标识" prop="changeHandType">
            <el-radio-group v-model="listQuery.changeHandType">
              <el-radio
                :label="item.code"
                v-for="item in $dict.getDictData('ChangeHandType')"
                :key="item.code"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="选择队列" prop="selectQueue">
            <el-select
              v-model="listQuery.selectQueue"
              placeholder="请选择"
              clearable
              @change="selectQueueChange"
              filterable
              class="select-queue"
            >
              <el-option
                v-for="item in selectQueueArr"
                :key="item.id"
                :label="item.queueName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!-- <add-agent
          v-if="listQuery.selectQueue"
          @close="
            agentClose();
            dialog.addAgent = false;
          "
          :showGuzhi="showGuzhi"
          :isTeamUse="true"
          :treeClose="false"
          :queueId="listQuery.queueId"
          ref="add-agent"
          @next="next"
          :teamUseQuery="teamUseQuery"
          :departmentData="departmentData"
          :userIds="agentId"
        ></add-agent> -->
        <add-agent-detail
          @next="next"
          :teamUseQuery="teamUseQuery"
          v-if="listQuery.selectQueue"
          @close="agentClose()"
          :showGuzhi="showGuzhi"
          :isTeamUse="true"
          :treeClose="false"
          :selectArr="selectArr"
          :queueId="listQuery.queueId"
          :queueType="queueTypes"
          ref="add-agent-detail"
          :departmentData="departmentData"
          :expandDefault="expandDefault"
          :isOuter="isOuter"
          :realArr="realArr"
        ></add-agent-detail>
      </el-form>
      <div v-show="!transferDialog">
        <data-box
          :data="confirmData"
          :key="1"
          ref="confirmData-box"
          class="confirm-data"
        >
          <template slot="columns">
            <el-table-column prop="currentCollectorCode" :label="isOuter ? '外包机构代码' : '经办代号'" />
            <el-table-column prop="currentCollectorRealName" :label="isOuter ? '外包名称' : '姓名'" />
            <el-table-column prop="entityNo" label="分配实体数量" />
            <el-table-column prop="caseNo" label="分配账户数量" />
            <el-table-column
              prop="caseMony"
              label="实体下参与分配账户金额"
              :formatter="row => $filter.toThousands(row.caseMony)"
            />
          </template>
        </data-box>
      </div>
      <el-row class="btn" v-if="!transferDialog">
        <el-button type="primary" @click="returnTransferDialog"
          >上一步</el-button
        >
        <el-button type="primary" @click="dialogCancel">取消</el-button>
        <el-button type="primary" @click="confirmTransferDialog"
          >确定</el-button
        >
      </el-row>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import AddAgent from "~/components/queue-manage/add-agent.vue";
import AddAgentDetail from "~/components/queue-manage/add-agent-detail.vue";
import { QueueService } from "~/services/domain-service/queue-manage.service";
import { Dependencies, Layout, Auth } from "~/core/decorator";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { PageService } from "~/utils/page.service";
import { SortService } from "~/utils/sort.service";
import { TelephoneCollectionService } from "~/services/domain-service/telephone-collection-controller.service";
import { TelCaseManageService } from "~/services/domain-service/tel-case-manage.service";
import { CaseInfoService } from "~/services/domain-service/case-info.service";
import { DepartmentService } from "~/services/management-service/department.service";

@Component({
  components: {
    AddAgent,
    AddAgentDetail
  }
})
export default class TransferDialog extends Vue {
  @Dependencies(CaseInfoService) private CaseInfoService: CaseInfoService;
  @Dependencies(TelCaseManageService) private TelCaseManageService: TelCaseManageService;
  @Dependencies(PageService) private pageService: PageService;
  @Dependencies(SortService) private sortService: SortService;
  @Dependencies(QueueService) private queueService: QueueService;
  @Dependencies(TelephoneCollectionService)
  private TelephoneCollectionService: TelephoneCollectionService;
  @Dependencies(DepartmentService)
  private departmentService: DepartmentService;
  @Prop({ required: true }) private dialogOpen: boolean;
  @Prop({ required: true }) private selectionList: any;
  @Prop() private allData: any;
  @Prop() private type: string;
  @Prop() private searchQuery: any;

  private rules: any = {
    distributionMode: [
      { required: true, message: "请选择分配模式", trigger: "change" }
    ],
    balanceWay: [
      { required: true, message: "请选择配平方式", trigger: "change" }
    ],
    balanceDimension: [
      { required: true, message: "请选择配平维度", trigger: "change" }
    ],
    state: [
      { required: true, message: "请选择非延滞账户参与配平", trigger: "change" }
    ],
    changeHandType: [
      { required: true, message: "请选择转手标识", trigger: "change" }
    ],
    selectQueue: [
      { required: true, message: "请选择选择队列", trigger: "change" }
    ]
  };
  private realArr: any = [];
  private selectArr: any = [];
  // private queueType: string = "";
  private confirmData: any[] = [];
  private showGuzhi: boolean = false;
  private dialogTitle: string = "案件转派";
  private transferDialog: boolean = true;
  private queueId: string = "";
  private expandDefault: any = "";
  private isOuter: boolean = false
  private flag: boolean = true;
  @Prop() private queueType;
  private queueTypes: any;
  private dialog = {
    addAgent: false
  };
  private listQuery: any = {
    handleSet: [],
    balanceDimension: "",
    balanceWay: "",
    changeHandType: "",
    distributionMode: "",
    lockEndDate: "",
    state: "",
    queueId: "",
    caseIds: [],
    selectQueue: ""
  };
  private teamUseQuery: any = {
    queueRemark: "",
    lockEndDate: "",
    expireDate: "",
    expireDay: "",
    expireMonth: ""
  };
  private selectQueueArr: any = [];
  private departmentData: any = [];
  private agentId: any = [];
  private selectArrChange: any = [];
  private allMsg: any = {}

  private get allMoney() {
    // 计算选择的总金额
    let num;
    const data = this.allData.length !== 0 ? this.allData : this.selectionList;
    return (num = data.reduce((prev, cur) => {
      return cur.caseMoney + prev;
    }, 0));
  }

  @Watch("dialogOpen", { immediate: true }) private manualDivision() {
    // 转派按钮
    if (this.dialogOpen) {
      this.findQueues();
      this.transferDialog = true;
      this.dialog.addAgent = true;
      this.dialogTitle = "案件转派";
      this.getSelectMsg()
    } else {
      this.allMsg = {}
      this.showGuzhi = false
    }
  }

  @Emit("agentClose") private agentClose() {} // 第一页的取消按钮
  @Emit("dialogCancel") private dialogCancel() {} // 第二页取消按钮

  private getSelectMsg() { // 获取选择的案件数和金额合计
    const obj = { // 要传的参数
      caseIds: [],
      isFullData: false
    }
    let api // 区分团队和待分配接口
    if(this.type === 'team') {
      api = this.TelCaseManageService
      obj['telTeamCasePoolRequest'] = {}
    } else {
      obj['caseSearchRequest'] = {}
      api = this.CaseInfoService
    }
    if(this.allData.length === 0) { // 非全选
      obj.caseIds = this.selectionList.map(e => e.id)
      obj.isFullData = false
    } else { // 全选
      for (const key in this.searchQuery) {
        if (this.searchQuery[key] === "") {
          delete this.searchQuery[key];
        }
      }
      this.type === 'team' ? obj['telTeamCasePoolRequest'] = this.searchQuery : obj['caseSearchRequest'] = this.searchQuery
      obj.isFullData = true
    }
    api.transferCaseAmount(obj).subscribe(
      data => {
        this.allMsg = data
      }
    )
  }

  private distributionModeChange(val) {
    // 分配模式选择
    this.showGuzhi = val === "FIXED_RATIO";
  }

  private confirmTransferDialog() {
    // 确定转派
    let apiType;
    this.type === "team"
      ? (apiType = this.TelephoneCollectionService)
      : this.type === "case"
      ? (apiType = this.CaseInfoService)
      : (apiType = this.queueService);
    apiType.telTransferCaseConfirm(this.listQuery).subscribe(
      data => {
        this.$message.success("操作成功");
        this.$emit("confirmTransferDialog");
      },
      err => {
        this.$message.error("操作失败");
      }
    );
  }

  private findQueues() {
    // 获取选中队列列表
    if(this.type === "team") {
      // this.TelephoneCollectionService.findQueuesByQueueType().subscribe(data => {
      //   this.selectQueueArr = data;
      // })
      if(this.queueType){
        // 队列-转派
        this.TelephoneCollectionService.findQueueListByType({ "channelCode": this.queueType }).subscribe(data => {
          this.selectQueueArr = data;
        })
      } else {
        // 电催-转派
        this.TelephoneCollectionService.findQueuesByQueueType().subscribe(data => {
          this.selectQueueArr = data;
        })
      }
    } else {
      this.TelephoneCollectionService.findAllValidQueues().subscribe(data => {
        this.selectQueueArr = data;
      })
    }
  }

  private selectQueueChange(val) {
    this.isOuter = this.selectQueueArr.filter(e => e.id === val)[0].queueCategory === 'OUTER' ? true : false
    this.queueTypes = this.selectQueueArr.filter(e => e.id === val)[0].queueCategory === 'OUTER' ? 'OUTER' : 'SELF'
    // 选择队列后触发
    if (val) {
      this.listQuery.queueId = val;
      this.$nextTick(() => {
        const addAgent: any = this.$refs["add-agent-detail"];
        addAgent.currentNode = null;
        addAgent.getAgentData();
        // 历史注记
        addAgent.queryHistory(this.listQuery.queueId );
        addAgent.numberValidateForm.remark = "";
        // 监听add-agent选中的数据
        addAgent.getAllDepartmentData();
        this.TelephoneCollectionService.getQueueInfo({ queueId: val }).subscribe(
          data => {
            this.teamUseQuery.queueRemark = data.queueRemark;
            this.teamUseQuery.lockEndDate = data.lockEndDate;
            this.teamUseQuery.expireMonth = data.expireMonth;
            this.teamUseQuery.expireDay = data.expireDay;
            this.teamUseQuery.expireDate = JSON.stringify(data.expireDate);
            // 解决自动勾选表格
            const arr = data.handleSet.map(item => {
              this.$set(item, 'fixedCount', '')
              this.$set(item, 'proportion', '')
              return {
                ...item,
                id: item.agentId
              };
            });
            this.realArr = arr
            this.agentId = data.handleSet.map(v => v.agentId);
            Promise.all([this.getQueryDepartmentByUserIds(this.agentId)]).then(
              () => (this.selectArr = arr)
            );
          }
        );
      });
    } else {
      this.agentId = "";
    }
  }

  private next(val, data) {
    let validate = true;
    if (this.listQuery.distributionMode === "FIXED_RATIO") {
      // val.every((item, index) => {
      //   //校验固值和比例
      //   if (!this.$validator.naturalNumber(item.fixedCount)) {
      //     this.$message.error(`第${index + 1}条固值需要为0或者正整数`);
      //     validate = false;
      //     return false;
      //   }
      //   item.fixedCount = Number(item.fixedCount);
      //   if (item.proportion === "" || item.proportion === null) {
      //     return true;
      //   } else if (
      //     !this.$validator.percentTwoDecimal(item.proportion) ||
      //     item.proportion === 0
      //   ) {
      //     this.$message.error(`第${index + 1}条比例需为0-100的两位数小数`);
      //     validate = false;
      //     return false;
      //   }
      //   item.proportion = Number(item.proportion);

      //   let totalProportion: any = 0;
      //   val.forEach(item1 => {
      //     totalProportion += Number(item1.proportion);
      //   });
      //   totalProportion = totalProportion === 0 ? "" : totalProportion;
      //   if (totalProportion !== 100 && totalProportion !== "") {
      //     this.$message.error("经办比例之和为空或等于100");
      //     validate = false;
      //     return false;
      //   }
      //   return true
      // });
      const emptyValueCount = val.filter(x => x.proportion === "").length
      if(emptyValueCount === 0){
        // 全部有值
         const totalProportion = val.reduce((sum, currentRow) => {
          const value = Number(currentRow.proportion || 0)
          return sum + value
        }, 0)

        if (totalProportion !== 100) {
          this.$message.error("比例总和应等于100")
          validate = false
          return false
        }
      }else if(emptyValueCount < val.length){
        // 部分有值
        const index = val.findIndex(x => !x.proportion)
        this.$message(`请输入第${index+1}行的比例值`)
        validate = false
      }

      val.every((item, index) => {
        //校验固值和比例
        // if (!this.$validator.naturalNumber(item.fixedCount)) {
        //   this.$message.error(`第${index + 1}条固值需要为0或者正整数`);
        //   validate = false;
        //   return false;
        // }
        item.fixedCount = Number(item.fixedCount);
        if (item.proportion === "" || item.proportion === null) {
          return true;
        } else if (
          !this.$validator.percentTwoDecimal(item.proportion) ||
          item.proportion === 0
        ) {
          this.$message.error(`第${index + 1}条比例需为0-100的两位数小数`);
          validate = false;
          return false;
        }
        return true
      });
    }
    if(validate) {
      // 下一步
      for (const key in this.searchQuery) {
        if (this.searchQuery[key] === "") {
          delete this.searchQuery[key];
        }
      }
      const ruleForm: any = this.$refs["ruleForm"];
      ruleForm.validate(valid => {
        if (valid) {
          this.dialogTitle = "确认转派";
          let selectData;
          if (this.allData.length !== 0) {
            selectData = this.allData;
            this.listQuery.isFullData = true;
            this.type === "team"
              ? (this.listQuery.telTeamCasePoolRequest = this.searchQuery)
              : this.type === "case"
              ? (this.listQuery.caseSearchRequest = this.searchQuery)
              : (this.listQuery.queueCasesRequest = this.searchQuery);
          } else {
            selectData = this.selectionList;
            this.listQuery.isFullData = false;
            this.type === "team"
              ? (this.listQuery.telTeamCasePoolRequest = {})
              : this.type === "case"
              ? (this.listQuery.caseSearchRequest = {})
              : (this.listQuery.queueCasesRequest = {});
          }
          this.listQuery.handleSet = val;
          this.listQuery.caseIds = selectData.map(e => e.id);
          this.listQuery = { ...this.listQuery, ...data };
          let apiType;
          this.type === "team"
            ? (apiType = this.TelephoneCollectionService)
            : this.type === "case"
            ? (apiType = this.CaseInfoService)
            : (apiType = this.queueService);
          apiType.telTransferCaseNext(this.listQuery).subscribe(data => {
            if (data) {
              this.transferDialog = false;
              this.confirmData = data;
            } else {
              this.$notify.error("请求结果为空");
            }
          });
        }
      });
    }
  }

  private dialogClose() {
    this.dialogTitle = "案件转派";
    this.transferDialog = true;
    this.listQuery = {
      handleSet: [],
      balanceDimension: "",
      balanceWay: "",
      changeHandType: "",
      distributionMode: "",
      lockEndDate: "",
      state: "",
      queueId: "",
      caseIds: [],
      selectQueue: ""
    };
    const ruleForm: any = this.$refs["ruleForm"];
    ruleForm.resetFields();
  }

  private returnTransferDialog() {
    // 确定转派弹框上一步按钮
    this.transferDialog = true;
    this.dialogTitle = "案件转派";
  }

  private getQueryDepartmentByUserIds(userIds) {
    if (this.agentId.length !== 0) {
      this.departmentService
        .queryDepartmentByUserIds({ userIds })
        .subscribe(data => {
          if (data.length !== 0) {
            this.departmentData = this.$common.generateTreeData(data, {
              keyName: "id",
              parentKeyName: "parentId"
            });
            this.expandDefault = this.departmentData[0].deptCode;
          }
        });
    }
  }
}
</script>
<style lang="less" scoped>
.confirm-data {
  width: 100%;
}
.select-queue {
  height: 26px;
}
.transfer-dialog-title {
  text-align: center;
  margin-bottom: 20px;
}
.btn {
  text-align: center;
  button {
    padding: 6px 20px;
    font-weight: 400;
    font-size: 12px;
    background: #3582fb;
    border-color: #3582fb;
  }
}
</style>
<style lang="less">
.transfer-dialog {
  .el-form-item__label {
    width: 160px !important;
  }
  .el-table__empty-block {
    width: 100% !important;
  }
  .el-form-item__error {
    left: 130px !important;
  }
}
</style>
